package cn.klaw.util;

import lombok.extern.slf4j.Slf4j;

import java.sql.Clob;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 在线详情编辑工具类
 *
 *
 * @version V3.2
 *
 * @date 2021/10/27
 */
@Slf4j
public class DataClob {

    public static List<Map<String, Object>> swapClob(List<Map<String, Object>> list) {
        if (list == null || list.isEmpty()) {
            return list;
        }
        List<Map<String, Object>> result = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            for (String key : map.keySet()) {
                swapClob(map, key);
            }
            result.add(map);
        }
        return result;
    }

    public static void swapClob(Map<String, Object> map, String key) {
        if (map != null && map.get(key) != null && map.get(key) instanceof Clob) {
            Clob clob = (Clob) map.get(key);
            StringBuilder sb = new StringBuilder();
            // 获取CLOB字段的内容长度
            int length = 0;
            // 以流的形式读取CLOB字段的内容
            try (java.io.Reader reader = clob.getCharacterStream()) {
                length = (int) clob.length();
                char[] buffer = new char[length];
                int bytesRead;
                // 逐个字符读取并添加到字符串构建器中
                while ((bytesRead = reader.read(buffer)) != -1) {
                    sb.append(buffer, 0, bytesRead);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put(key, sb.toString());
        }
    }
}
